<?php

namespace app\admin\controller;

use app\admin\controller\BaseController;
use think\Db;
use think\Request;
use think\Validate;

class Dict extends BaseController
{
    // 设置模型名称
    protected $modelName = 'dict';

    protected $uniqueFields = ['name'];

    protected $fieldLabels = [
        'name' => '字典名',
    ];

    // 设置验证规则
    // 添加自定义string验证规则
    public function __construct()
    {
        parent::__construct();
        Validate::extend('string', function ($value) {
            return is_string($value);
        }, '必须是字符串类型');
    }

    // 设置验证规则
    protected $validateRules = [
        'id' => 'number',
        'name' => 'require|max:10',
        'desc' => 'max:100',
    ];

    // 设置规则提示
    protected $validateRulesMsg = [
        'name.require' => '字典名不能为空',
        'name.max' => '字典名最多10个字符',
        'desc.max' => '字典描述最多100个字符',
    ];

    public function getList()
    {
        $list = $this->model->order('sort asc')->select();
        if ($list) {
            foreach ($list as &$v) {
                $dict_item = Db::name('dict_item')->where('dict_id', $v['id'])->order('id asc')->select();
                $v['dictItem'] = $dict_item ?: [];
            }
        }
        apiReturn(1, '获取成功', $list);
    }
}
